#!/bin/bash
# Git checkpoint hook script
# This script is executed on Stop and UserPromptSubmit events

# Read JSON input from stdin
INPUT=$(cat)

# Get the project directory from Claude Code environment
# If not available, default to current directory
PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$(pwd)}"

# Change to the project directory
cd "$PROJECT_DIR" || exit 0

# Only proceed if we're in a git repository
if ! git rev-parse --git-dir > /dev/null 2>&1; then
  exit 0
fi

# First, commit any already staged changes
if ! git diff --cached --quiet; then
  echo "checkpoint staged changes"
  git commit -m "checkpoint: Auto-commit staged changes"
fi

# Then, add unstaged changes and commit them separately
if ! git diff-index --quiet HEAD -- || [ -n "$(git ls-files --others --exclude-standard)" ]; then
  echo "checkpoint unstaged changes"
  git add -A
  git commit -m "checkpoint: Auto-commit unstaged changes"
fi

exit 0